package com.shop.cloud.controller.system;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.shop.cloud.common.mybatis.BaseController;
import com.shop.cloud.common.token.PasswordHashUtil;
import com.shop.cloud.dao.system.SysUserDao;
import com.shop.cloud.domain.system.SysPosition;
import com.shop.cloud.domain.system.SysResource;
import com.shop.cloud.domain.system.SysRole;
import com.shop.cloud.domain.system.SysUser;
import com.shop.cloud.domain.system.SysUserRole;
import com.shop.cloud.filter.CurrentUserId;
import com.shop.cloud.filter.MagicPermission;
import com.shop.cloud.model.request.AddSysUserRequest;
import com.shop.cloud.model.request.DeleteSysUserRequest;
import com.shop.cloud.model.request.EditSysUserRequest;
import com.shop.cloud.model.request.GetSysUserListRequest;
import com.shop.cloud.model.response.AddSysUserResponse;
import com.shop.cloud.model.response.DeleteSysUserResponse;
import com.shop.cloud.model.response.EditSysUserResponse;
import com.shop.cloud.model.response.GetSysUserListResponse;
import com.shop.cloud.model.response.ObjectDataResponse;
import com.shop.cloud.security.EncodeUtil;
import com.shop.cloud.service.system.ISysPositionService;
import com.shop.cloud.service.system.ISysRoleService;
import com.shop.cloud.service.system.ISysUserRoleService;
import com.shop.cloud.service.system.ISysUserService;
import com.shop.cloud.util.DateUtils;
import com.shop.cloud.util.ErrorCode;
import com.shop.cloud.util.Page;
import com.shop.cloud.util.Response;
import com.shop.cloud.util.ResponseUtil;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "sysuser")
public class SysUserController extends BaseController {

	private static final Logger logger=Logger.getLogger(SysUserController.class);
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	
	@Autowired
	private ISysRoleService sysRoleService;
	
	@Autowired
	private ISysPositionService sysPositionService;
	
	@Autowired
	private SysUserDao sysUserDao;
	
	@RequestMapping(value = "resetPassword", method = RequestMethod.POST)
	@ResponseBody
	public Response resetPassword(HttpServletRequest request,SysUser member){
		member.setPassword("123456");
		return ResponseUtil.ok(sysUserService.updatePassword(member));
	}
	
	@MagicPermission
	@RequestMapping(value = "find", method = RequestMethod.POST)
	@ResponseBody
	public Response find(@CurrentUserId Long userId,HttpServletRequest request){
		Map<String, Object> params=getPageMap(request);
		Page<SysUser> datas=sysUserService.page(params);
		return ResponseUtil.ok(datas);
	}
	
	@ApiOperation(value = "查询后台用户管理" , notes="查询后台用户管理")
	@RequestMapping(value = "queryUserList", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Page<SysUser>> queryUserList(@CurrentUserId Long userId,@RequestBody SysUser sysUser){
		
		sysUser.setId(userId);
		Page<SysUser> datas= sysUserService.queryUser(sysUser);
	
		return new ObjectDataResponse<Page<SysUser>>(datas);
	}
	
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public Response list(HttpServletRequest request, HttpServletResponse response, @RequestBody GetSysUserListRequest sysUserListRequest){
		Map<String, Object> map = new HashMap<String, Object>();
		long count = 0;
		List<GetSysUserListResponse> datas = new ArrayList<GetSysUserListResponse>();
		GetSysUserListResponse data = null;
		Map<String, Object> params=getPageMapNew(request,sysUserListRequest.getPageSize_(),sysUserListRequest.getPageIndex_());
		params.put("status", 0);
		if(!(sysUserListRequest.getName() == null || sysUserListRequest.getName().equals(""))){
			params.put("fullname", sysUserListRequest.getName());
		}

		if(!(sysUserListRequest.getPosition() == null || sysUserListRequest.getPosition().equals("")))
			params.put("positionId", sysUserListRequest.getPosition());
		if(!(sysUserListRequest.getRole() == null || sysUserListRequest.getRole().equals("")))
			params.put("roleId", sysUserListRequest.getRole());
		if(!(sysUserListRequest.getStart_time() == null || sysUserListRequest.getStart_time().equals("")))
			params.put("startTime", sysUserListRequest.getStart_time());
		if(!(sysUserListRequest.getEnd_time() == null || sysUserListRequest.getEnd_time().equals("")))
			params.put("endTime", sysUserListRequest.getEnd_time());
		List<SysUser> sysUsers=sysUserService.find(params);
		//不行就加一个 查询总条数的sql
//		List<SysUser> sysUsers1=sysUserService.find(params1);
		SysUserRole sysUserRole = null;
		SysRole sysRole = null;
		SysPosition sysPosition = null;
		SysUser sysUser = null;
		int i = 0;
		if(sysUsers != null) {
			count=sysUserService.findCount(params);

			for(i = 0 ; i < sysUsers.size() ; i++) {
				sysUser = sysUsers.get(i);
				data = new GetSysUserListResponse();
				data.setId(sysUser.getId());
				data.setUsername(sysUser.getUsername());
				data.setFullname(sysUser.getFullname());
				data.setCreate_time(sysUser.getCreateDate());
				data.setLast_login_time(sysUser.getCreateDate());
				data.setRole("");
				data.setPosition("");
				
				params = new HashMap<String, Object>();
				params.put("userId", sysUser.getId());
				sysUserRole = sysUserRoleService.findOne(params);
				if(sysUserRole != null) {
					params = new HashMap<String, Object>();
					params.put("id", sysUserRole.getRoleId());
					sysRole = sysRoleService.findOne(params);
					if(sysRole != null) {
						data.setRole(sysRole.getName());
					}
					params = new HashMap<String, Object>();
					params.put("id", sysUserRole.getPositionId());
					sysPosition = sysPositionService.findOne(params);
					if(sysPosition != null) {
						data.setPosition(sysPosition.getName());
					}
				}
				datas.add(data);
			}
			
		
		}
		
		map.put("data", datas);
		map.put("pageCount", count);
		
		return ResponseUtil.ok(map);
	}
	
//	      "id": 22, 
//	      "username": "admin",
//	      "fullname": "超级管理员",
//	      "role": "总部",
//	      "position": "职位1",
//	      "create_time": 1507564800000,
//	      "last_login_time": 1507564800000
	 
	
	@RequestMapping(value = "querylist", method = RequestMethod.POST)
	@ResponseBody
	public  ObjectDataResponse<List<SysResource>> querylist(@CurrentUserId Long userId,@RequestBody SysResource sysResource){
		
		
		return null;
	}
//	
	//@MagicPermission
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public Response update(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody EditSysUserRequest editSysUserRequest){
		EditSysUserResponse editSysUserResponse = new EditSysUserResponse();
		SysUser sysUser = null;
		SysUserRole sysUserRole = new SysUserRole();
		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
		Map<String, Object> params = null;
		Long id = 0L;
		
		if(editSysUserRequest.getId().equals("") ||
		   editSysUserRequest.getUsername().equals("") ||
		   editSysUserRequest.getFullname().equals("") ||
		   editSysUserRequest.getPosition().equals("") ||
		   editSysUserRequest.getRole().equals("")) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "所有项都必填");
		}
		
		if(Long.parseLong(editSysUserRequest.getRole()) <= 0) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "请选择角色类型");
		}
		
		if(Long.parseLong(editSysUserRequest.getPosition()) <= 0) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "请选择角色职位");
		}
		
		id = Long.parseLong(editSysUserRequest.getId());
		
		params = new HashMap<String, Object>();
		params.put("equsername", editSysUserRequest.getUsername());
		sysUser = sysUserService.findOne(params);
		if(sysUser != null) {
			if(sysUser.getId() != id) {
				return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "登录帐号已存在");
			}
		}
		
		params = new HashMap<String, Object>();
		params.put("id", id);
		sysUser = sysUserService.findOne(params);
		if(sysUser == null) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "id不存在");
		}
		
		sysUser.setFullname(editSysUserRequest.getFullname());
		sysUser.setUsername(editSysUserRequest.getUsername());
		sysUser.setUpdateDate(currentTime);
		sysUser.setUpdateUser(userId);
		
		if(!(editSysUserRequest.getPassword() == null || editSysUserRequest.getPassword().equals(""))) {
			sysUser.setPassword(editSysUserRequest.getPassword());
		}
		sysUserService.update(sysUser);
		
		params = new HashMap<String, Object>();
		params.put("user_id", id);
		sysUserRole = sysUserRoleService.findOne(params);
		if(sysUserRole == null) {
			sysUserRole = new SysUserRole();
			sysUserRole.setUserId(sysUser.getId());
			sysUserRole.setRoleId(Long.parseLong(editSysUserRequest.getRole()));
			sysUserRole.setPositionId(Long.parseLong(editSysUserRequest.getPosition()));
			sysUserRoleService.insert(sysUserRole);
		} else {
			sysUserRole.setUserId(sysUser.getId());
			sysUserRole.setRoleId(Long.parseLong(editSysUserRequest.getRole()));
			sysUserRole.setPositionId(Long.parseLong(editSysUserRequest.getPosition()));
			sysUserRoleService.update(sysUserRole);
		}
		
		return ResponseUtil.ok(editSysUserResponse);
	}
	
	@ApiOperation(value = "GMC用户修改内容", notes = "用户修改")
	@RequestMapping(value = "updateSysUser", method = RequestMethod.POST)
	@ResponseBody
	public Response updateSysUser(@RequestBody SysUser sysUser) {
		SysUserRole sysUserRole = new SysUserRole();
		sysUserRole.setUserId(sysUser.getId());
		sysUserRole.setId(sysUserRoleService.find(sysUserRole).get(0).getId());
		sysUserRole.setRoleId(new Long(sysUser.getRoleId()));
		sysUserRole.setPositionId(new Long(sysUser.getPositionId()));
		
		
	    sysUserRoleService.update(sysUserRole);
	    
		int success  = sysUserService.update(sysUser);
		return  ResponseUtil.ok(success);
	}
	
	@RequestMapping(value = "updateUserInfo", method = RequestMethod.POST)
	@ResponseBody
	public Response updateUserInfo(@CurrentUserId Long userId,HttpServletRequest request,SysUser sysUser){
		Date date = DateUtils.getSysDate();
		//sysUser.setUpdateDate(date);
		sysUser.setUpdateUser(userId);
		sysUserService.update(sysUser);
		return ResponseUtil.ok();
	}
	
	@RequestMapping(value = "updatePassword", method = RequestMethod.POST)
	@ResponseBody
	public Response updatePassword(@CurrentUserId Long userId,HttpServletRequest request,SysUser sysUser,String oldPassword){
		Date date = DateUtils.getSysDate();
		if(!StringUtils.isEmpty(oldPassword)){
			SysUser user=sysUserService.get(userId);
			try {
				if(PasswordHashUtil.validatePassword(oldPassword, user.getPassword())){
					//sysUser.setUpdateDate(date);
					sysUser.setId(userId);
					sysUser.setUpdateUser(userId);
					sysUserService.updatePassword(sysUser);
					return ResponseUtil.ok();
				}else {
					return ResponseUtil.error(ErrorCode.USER_PASSWORD_NOT_EQUALS);
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
			}
		}
		return ResponseUtil.error();
	}
	
	//@MagicPermission
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Response add(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody AddSysUserRequest addSysUserRequest){
		AddSysUserResponse addSysUserResponse = new AddSysUserResponse();
		SysUser sysUser = null;
		SysUserRole sysUserRole = new SysUserRole();
		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
		Map<String, Object> params = null;
		
		if(addSysUserRequest.getUsername().equals("") ||
		   addSysUserRequest.getFullname().equals("") ||
		   addSysUserRequest.getPassword().equals("") ||
		   addSysUserRequest.getPosition().equals("") ||
		   addSysUserRequest.getRole().equals("")) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "所有项都必填");
		}
		
		params = new HashMap<String, Object>();
		params.put("username", addSysUserRequest.getUsername());
		sysUser = sysUserDao.findUserByName(params);
		if(sysUser != null) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "已存在此账号");
		}
		
		sysUser = new SysUser();
		sysUser.setUsername(addSysUserRequest.getUsername());
		sysUser.setPassword(EncodeUtil.encodeMD5(addSysUserRequest.getPassword()));
		sysUser.setFullname(addSysUserRequest.getFullname());
		sysUser.setGender(1);
		sysUser.setPhone("");
		sysUser.setDepartmentId("0");
		sysUser.setImage("0");
		sysUser.setStatus(0);
		sysUser.setCreateUser(userId);
		sysUser.setUpdateUser(userId);
		sysUser.setCreateDate(currentTime);
		sysUser.setUpdateDate(currentTime);
		if(!sysUserService.insert(sysUser)) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "插入失败");
		}
		
		params = new HashMap<String, Object>();
		params.put("username", addSysUserRequest.getUsername());
		sysUser = sysUserDao.findUserByName(params);
		sysUserRole.setUserId(sysUser.getId());
		sysUserRole.setRoleId(Long.parseLong(addSysUserRequest.getRole()));
		sysUserRole.setPositionId(Long.parseLong(addSysUserRequest.getPosition()));
		if(!sysUserRoleService.insert(sysUserRole)) {
			params = new HashMap<String, Object>();
			params.put("username", addSysUserRequest.getUsername());
			sysUser = sysUserService.findOne(params);
			sysUserService.remove(sysUser);
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "插入失败");
		}
		
		return ResponseUtil.ok(addSysUserResponse);
	}

 	//@MagicPermission
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public Response delete(@CurrentUserId Long userId,HttpServletRequest request, HttpServletResponse response, @RequestBody DeleteSysUserRequest deleteSysUserRequest){
		DeleteSysUserResponse deleteSysUserResponse = new DeleteSysUserResponse();
		Map<String, Object> params = null;
		params = new HashMap<String, Object>();
		params.put("id", deleteSysUserRequest.getId());
		
		
		SysUserRole sysuserrole = new SysUserRole();
		sysuserrole.setUserId(new Long(deleteSysUserRequest.getId()));
		sysUserRoleService.remove(sysuserrole);
		
		sysUserService.remove(params);
		return ResponseUtil.ok(deleteSysUserResponse);
	}

}